package com.java.basic;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadPoolExecutorTest {

    public static void main(String[] args){
        AtomicInteger atomicInteger = new AtomicInteger(0);
        int corePoolSize =3;
        int maximumPoolSize = 10;
        long keepAliveTime = 60 ;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(2);
        ThreadFactory threadFactory = new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                try {
                    TimeUnit.MICROSECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Thread thread = new Thread(r,"线程："+atomicInteger.addAndGet(1));
                return thread;
            }
        };
        RejectedExecutionHandler handler  = new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                System.out.println("RejectedExecutionHandle​{"+r.toString()+"}");
               // System.out.println("拒绝数据");
            }
        };
        /*
        AbortPolicy：丢弃任务，并抛出RejectedExecutionException异常（需要在调用线程处捕获异常，即执行submit线程处）
        DiscardPolicy：丢弃任务，不抛出异常
        DiscardOldestPolicy：丢弃等待队列最前面任务
        CallerRunsPolicy：由调用线程处理该任务
        */

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTime,unit,workQueue,threadFactory, handler);
        for(int i=0;i<50;i++){
            threadPoolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("当前执行线程:"+Thread.currentThread().getName());
                    try {
                        TimeUnit.SECONDS.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        threadPoolExecutor.shutdown();
    }

}
